<template>
  <el-container>
    <el-header>
      工具栏
    </el-header>
    <el-main>
      <svg id="mind" xmlns="http://www.w3.org/2000/svg" width="500px" height="500px" style="background-color: aqua">
        <g v-html="mindVal"></g>
        <foreignObject id="editorForeign" x="0" y="0" width="0" height="0">
          <input id="editorInput" type="text" style="width: 100px;display: none;text-align:center" />
        </foreignObject>
      </svg>
    </el-main>
  </el-container>
</template>

<script>
import $ from "jquery";
import { vsprintf } from "sprintf-js";
const rectTemplate = "<rect tag=\"svg_rect\" height=\"%d\" width=\"%d\" x=\"%d\" y=\"%d\" rx=\"%d\" style=\"%s\"/>";
const textTemplate = "<text id=\"%d\" tag=\"svg_text\" x=\"%d\" y=\"%d\" style=\"%s\">%s</text>";

export default {
  name: "MindMap",
  mounted() {
    $("text[tag='svg_text']").on('dblclick', function () {
      $("#editorForeign").attr("x", $(this).attr("x") - 50);
      $("#editorForeign").attr("y", $(this).attr("y") - 15);
      $("#editorForeign").attr("width", "100");
      $("#editorForeign").attr("height", "20");
      $("#editorInput").val($(this).text());
      $("#editorInput").show();
      $("#editorInput").focus();
    });
    $("#editorInput").blur(function () {
      $("#1").text($(this).val());
      $(this).hide();
      $("#editorForeign").attr("width", "0");
      $("#editorForeign").attr("height", "0");
    });
  },
  methods: {
  },
  data: function () {
    let render = function (node) {
      let html = "";
      if (node.type === "neuron") {
        let rect = node.rect;
        let text = node.text;
        html += vsprintf(rectTemplate, [rect.height, rect.width, rect.x, rect.y, rect.rx, rect.style]);
        html += vsprintf(textTemplate, [text.id, text.x, text.y, text.style, text.val]);
      }
      for (let i = 0; i < node.children.length; i++) {
        html += this.init(node.children[i]);
      }
      return html;
    }
    let root = {
      type: "neuron",
      rect: {
        height: 30,
        width: 120,
        x: 190,
        y: 235,
        rx: 5,
        style: "fill: #73a1bf;stroke-width: 2;stroke-linecap: round;stroke: black;"
      },
      text: {
        id: 1,
        x: 250,
        y: 256,
        val: "根",
        style: "fill: white;text-anchor: middle;"
      },
      children: []
    };
    return {
      mindVal: render(root)
    }
  }
}
</script>

<style scoped>
</style>